import { createHashRouter, Navigate } from "react-router";
import DefaultLayout from "../layout";
import { createElement } from "react";

const pages = import.meta.glob("/src/pages/**/*.{router.tsx,router.jsx}", {
  eager: true,
});

// 动态加载 meta 文件
// 匹配所有 .meta.ts 或 .meta.js 文件
const metas = import.meta.glob("/src/pages/**/*.meta.{ts,js}", { eager: true });

// 动态加载布局组件
const layoutModules = import.meta.glob("/src/layout/*.tsx", { eager: true });
const layouts = Object.fromEntries(
  Object.entries(layoutModules).map(([path, module]) => {
    // 如果是 index.tsx，使用 DefaultLayout 作为键名
    const name = path.endsWith("/index.tsx")
      ? "DefaultLayout"
      : path.match(/\/layout\/(.*)\.tsx$/)?.[1];
    return [name || "DefaultLayout", (module as any).default];
  })
);

// console.log(pages);
// console.log(metas);
// console.log(layouts);

const generateRoutes = (basePath = "/src/pages") => {
  const routeMap = {};

  Object.entries(pages).forEach(([path, component]) => {
    const pagePath = path
      .replace(basePath, "")
      .replace(/\/index\.router\.(tsx|jsx)$/, "")
      .toLowerCase();
    const metaPath = path.replace(/\.router\.(tsx|jsx)$/, ".meta.ts");
    // @ts-ignore
    const meta = metas[metaPath] ? metas[metaPath].default : {};

    const obj = {
      path: pagePath,
      element: createElement(component?.default),
      handle: meta,
      children: [],
    };

    routeMap[pagePath] = obj;
  });

  const transfData = convertToRoutesArray(routeMap);

  return transfData;
};

const convertToRoutesArray = (data, rootRedirect = "/home") => {
  console.log(data);
  // 1. 创建一个 Map，用于快速访问路径节点
  const pathMap = new Map();

  // 2. 初始化所有路径为 Map 节点
  for (const path in data) {
    pathMap.set(path, { path, ...data[path], children: [] });
  }

  // 3. 构建层级结构
  const rootPaths: any = [];
  pathMap.forEach((currentNode, path) => {
    // /home
    const parentPath = path.substring(0, path.lastIndexOf("/")) || "/"; // 计算父路径

    // 判断是否有父路径
    if (pathMap.has(parentPath) && path !== parentPath) {
      // 如果有父路径，将当前节点变为其父节点的子节点
      pathMap.get(parentPath).children.push(currentNode);
    } else {
      // 如果没有父路径，说明它是一个顶层路径
      rootPaths.push(currentNode);
    }
  });

  const defaultLayout = layouts["DefaultLayout"];
  const result = [
    {
      path: "/",
      children: Object.values(rootPaths),
      handle: {
        index: true,
        redirect: rootRedirect,
      },
      element: defaultLayout
        ? createElement(defaultLayout, null)
        : createElement("div", null),
    },
  ];

  console.log(result);

  return processRoutes(result);
};

const processRoutes = (routes) => {
  return routes.map((item) => {
    // 如果 item 的 handle 中存在 redirect 字段
    if (item.handle?.redirect) {
      const redirectPath = item.handle.redirect;

      // 如果 children 不存在，则初始化为空数组
      item.children = item.children || [];

      // 在 children 中添加一项 { index: true, element: <Navigate to={redirect} /> }
      item.children.unshift({
        index: true,
        element: <Navigate to={redirectPath} />,
      });
    }

    if (item.handle?.layout && item.element) {
      const layoutName = item.handle?.layout;
      const layoutModule = layouts[layoutName];

      item.element = createElement(layoutModule, null, item.element);
      console.log(layouts, layoutName);
    }

    // 如果 item 存在 children，递归处理子节点
    if (item.children && item.children.length > 0) {
      item.children = processRoutes(item.children);
    }

    return item;
  });
};

const routes = generateRoutes();
console.log(routes);

export const router = createHashRouter(routes);
